package com.xx.ems.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.xx.ems.model.Action;
import com.xx.ems.model.Roles;
import com.xx.ems.model.Users;
import com.xx.ems.service.PermissionsService;
import com.xx.ems.system.BaseService;

@Service(value="permissionsService")
public class PermissionsServiceImpl extends BaseService implements PermissionsService {
	@Override
	public boolean addPermissons(String actionids, Roles role, Users loginuser) {
		try{
			getTransaction().begin();
			getPermissionsDao().addPermissons(actionids.split(","), role, loginuser);
			getTransaction().commit();
			return true;
		}catch (Exception e) {
			e.printStackTrace();
			getTransaction().rollback();
			return false;
		}
	}

	@Override
	public boolean updatePermissions(String oldactionids, String newactionids, Roles role, Users loginuser) {
		try{
			getTransaction().begin();
			String[] oldactionidArray = oldactionids.split(",");
			String[] newactionidArray = newactionids.split(",");
			getPermissionsDao().updatePermissions(oldactionidArray, newactionidArray, role, loginuser);
			getTransaction().commit();
			return true;
		}catch (Exception e) {
			e.printStackTrace();
			getTransaction().rollback();
			return false;
		}
	}

	@Override
	public boolean deletePermissions(String roleid) {
		try{
			getTransaction().begin();
			getPermissionsDao().deletePermissions(roleid);
			getTransaction().commit();
			return true;
		}catch (Exception e) {
			e.printStackTrace();
			getTransaction().rollback();
			return false;
		}
	}
	
	@Override
	public boolean authorizeToUsers(String userids, String roleid) {
		try{
			getTransaction().begin();
			String[] useridArray = userids.split(",");
			getPermissionsDao().authorizeToUsers(useridArray, roleid);
			getTransaction().commit();
			return true;
		}catch (Exception e) {
			e.printStackTrace();
			getTransaction().rollback();
			return false;
		}
	}
	
	@Override
	public List<Object> getAllPermissions() {
		List<Action> actionList = getPermissionsDao().getAllPermissions();
		List<Object> actionMap = new ArrayList<Object>();
		/**
		 * 将action对象转换成map类型,这是为了使传到前台的json格式便于使用
		 */
		for (Action action : actionList) {
			actionMap.add(action.toHashMap());
		}
		return actionMap;
	}

	@Override
	public Map<String, Object> getRolesList(int pageNow, int maxCount) {
		return getPermissionsDao().getRolesList(pageNow, maxCount);
	}

	@Override
	public List<Object> getActionsByRoleid(int rid) {
		return getPermissionsDao().getActionsByRoleid(rid);
	}
}